package dao

import (
	"log"
	"testhttp/datasource"
	"testhttp/model"
	"time"
)

func ListTemp(searchparams string, pagesize, page int) []model.OrderTemp {
	res := make([]model.OrderTemp, 0)
	offset := (page - 1) * pagesize

	err := datasource.InstanceMaster().Cols("temp_uid", "temp_name", "dealer_id").Where(searchparams).Limit(pagesize, offset).GroupBy("temp_name").Find(&res)
	if err != nil {
		log.Print("Error ListOrderTemp()find:", err)
	}
	// log.Print("Debug OrderTemp page&pagesize:", page, pagesize, res)
	return res

}
func TempListforSelect(searchparams string) []model.OrderTemp {
	res := make([]model.OrderTemp, 0)

	err := datasource.InstanceMaster().Cols("temp_uid", "temp_name", "dealer_id").Where(searchparams).GroupBy("temp_name").Find(&res)
	if err != nil {
		log.Print("Error TempListforSelect()find:", err)
	}
	// log.Print("Debug TempListforSelect:", res)
	return res
}

func DelTemp(ordertemp []model.OrderTemp) {
	t := time.Now()

	del := &model.OrderTemp{IsDeleted: 1, UpdateTime: t}
	for x := 0; x < len(ordertemp); x++ {
		affected, err := datasource.InstanceMaster().Where("temp_uid = ?", ordertemp[x].TempUid).Update(del)
		log.Printf("%d records updated.\n", affected)
		if err != nil {
			log.Print("Debug query data:", ordertemp, err)
		}
	}
}

func AddTemp(ordertemp []model.OrderTemp) error {
	affected, err := datasource.InstanceMaster().Insert(ordertemp)
	log.Printf("%d records inserted.\n", affected)
	if err != nil {
		log.Print("AddTemp Error:", err)
	}
	return err
}

func GetTemp(uid string) []model.OrderTemp {
	ExcelHead := make([]model.OrderTemp, 0)
	err := datasource.InstanceMaster().Where("temp_uid =?", uid).Find(&ExcelHead)
	if err != nil {
		log.Print(ExcelHead)
	}

	return ExcelHead
}

func GetTempName(id string) string {
	res := make([]model.OrderTemp, 0)
	err := datasource.InstanceMaster().Where("temp_uid =?", id).Find(&res)
	if err != nil {
		log.Print("Error GetTempName:", err)
	}
	log.Print("Debug res:", res)
	if len(res) == 0 {
		name := "Null"
		return name
	} else {
		name := res[0].TempName
		return name
	}

}
